"""
ASGI config for devops project.

It exposes the ASGI callable as a module-level variable named ``application``.

For more information on this file, see
https://docs.djangoproject.com/en/3.2/howto/deployment/asgi/
"""

import os
import django
from django.core.asgi import get_asgi_application

os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'devops.settings')

# 初始化Django
django.setup()

# 现在可以安全地导入Django相关模块
from channels.routing import ProtocolTypeRouter, URLRouter
from cmdb.routing import websocket_urlpatterns as cmdb_websocket_urlpatterns
from monitoring.routing import websocket_urlpatterns as monitoring_websocket_urlpatterns
from docker_management.routing import websocket_urlpatterns as docker_websocket_urlpatterns
from cmdb.websocket_auth import TokenAuthMiddlewareStack

# 获取Django ASGI应用
django_asgi_app = get_asgi_application()

# 合并所有WebSocket URL模式
all_websocket_urlpatterns = cmdb_websocket_urlpatterns + monitoring_websocket_urlpatterns + docker_websocket_urlpatterns

# 直接使用标准的ProtocolTypeRouter
application = ProtocolTypeRouter({
    "http": django_asgi_app,  # 所有HTTP请求（包括SSE）都交给Django处理
    "websocket": TokenAuthMiddlewareStack(
        URLRouter(
            all_websocket_urlpatterns
        )
    ),
})
